package com.example.basic.cmdprocess;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ProcessBuilderExecutor {
	
	private String[] commands = null;
	private long timeoutMs = 01;
	private CountDownLatch countDownLatch = new CountDownLatch(1);
	private Process process;
	private boolean logprint;
	private InputStreamLineParser lineParser;
	private String[] breakStrings;
	
	public ProcessBuilderExecutor(String[] commands, long timeoutMs, String[] breakStrings) {
		this.commands = commands;
		this.timeoutMs = timeoutMs;
		this.breakStrings = breakStrings;
	}
	
	public void execute() {
		try {
			ProcessBuilder processBuilder = new ProcessBuilder();
			processBuilder.command(commands);
			processBuilder.redirectErrorStream(true);
			process = processBuilder.start();
			lineParser = new InputStreamLineParser(process.getInputStream(), countDownLatch, logprint, breakStrings);
			lineParser.start();
			countDownLatch.await(timeoutMs,TimeUnit.MILLISECONDS);
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}finally {
			if(lineParser != null) {
				lineParser.interrupt();
			}
			
			if(process != null) {
				process.destroy();
				process = null;
			}
		}
	}
	
	
	public void cancleExector() {
		if(countDownLatch != null) {
			countDownLatch.countDown();
		}
	}

	public List<String> getResult() {
		if(lineParser != null) {
			return lineParser.getResult();
		}
		return null;
	}

}
